package com.inifitness.tenant.core.config.mp.handler;

import java.util.List;
import java.util.Objects;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.inifitness.common.constants.GlobalConstants;
import com.inifitness.tenant.core.security.util.SecurityUtils;

import lombok.extern.log4j.Log4j2;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.expression.NullValue;
import net.sf.jsqlparser.schema.Column;

/**
 * 租户隔离插件
 *
 * @author sunjinfeng
 * @version 1.0
 * @since 2024/2/29 13:57
 */
@Log4j2
public class CustomTenantHandler implements TenantLineHandler {

  @Override
  public Expression getTenantId() {
    Long tenantId = SecurityUtils.getTenantId();
    if (Objects.isNull(tenantId)) {
      return new NullValue();
    }
    return new LongValue(tenantId);
  }

  @Override
  public String getTenantIdColumn() {
    return GlobalConstants.SYSTEM_TENANT_ID;
  }

  @Override
  public boolean ignoreTable(String tableName) {
//        //2024-05-09 SJF 这里改用注解方式
//        if (tableName.startsWith("sys_")) {
//            return true;
//        }
//        return TenantLineHandler.super.ignoreTable(tableName);

    if (Objects.nonNull(MybatisTenantContext.get())) {
      log.info("是否做租户隔离:{}", MybatisTenantContext.get());
      return MybatisTenantContext.get();
    }
    //默认租户隔离
    return false;

  }

  @Override
  public boolean ignoreInsert(List<Column> columns, String tenantIdColumn) {
    return TenantLineHandler.super.ignoreInsert(columns, tenantIdColumn);
  }
}
